//
//  JSTStartView.m
//  JSTMobClick
//
//  Created by 01 on 16/9/20.
//  Copyright © 2016年 Czj. All rights reserved.
//

#import "JSTStartView.h"
#import "JSTAdWebViewController.h"
static float pathValue = 0.;
typedef void(^touchOffBlock)();
typedef void(^touchChangeBlock)();
@interface JSTStartView ()

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UILabel *label;

@property (nonatomic, strong) touchOffBlock endBlock;

@property (nonatomic, strong) touchChangeBlock changePageBlock;

@property (nonatomic, strong) JSTHomePageModel *model;

@property (nonatomic, strong) UIImageView *adImgView;

@property (nonatomic, strong) UIImageView *otherImgView;

@property (nonatomic, strong) JSTLoopProgressView *loopProgressView;

@end
@implementation JSTStartView

- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        self.frame = [UIScreen mainScreen].bounds;
    }
    return self;
}
- (void) createContent:(JSTHomePageModel *)model end:(void (^)())end changePage:(void (^)())changPage{
    _model = model;
    NSArray *data = [JSTFMDBManager querySqlforTab:[JSTStartViewData modelWith:nil adImgUrl:nil disseminateImgUrl:nil]];
    if (data.count != 0) {
        JSTStartViewData *model = data[0];
        if (IsStrEmpty(model.adImgUrl) || IsStrEmpty(model.disseminateImgUrl)){
            end();
            [self removeFromSuperview];
            ((AppDelegate *)[UIApplication sharedApplication].delegate).startViewNeedOpen = YES;
            return;
        }
        [self.adImgView sd_setImageWithURL:[NSURL URLWithString:model.adImgUrl] placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
        [self.otherImgView sd_setImageWithURL:[NSURL URLWithString:model.disseminateImgUrl] placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSDictionary * stataDic = [userDefaults valueForKey:@"tableScreenData"];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"event"] = @"view";
        [JSTServer requestPostStatisticsData:dict postInterface:stataDic[@"url"] dataDic:nil errorStr:nil];
    }else {
        end();
        [self removeFromSuperview];
        ((AppDelegate *)[UIApplication sharedApplication].delegate).startViewNeedOpen = YES;
        return;
    }
    [self addSubview:self.adImgView];
    [self addSubview:self.otherImgView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changePage)];
    [self.adImgView addGestureRecognizer:tap];
    [self createTimer];
    self.endBlock = ^(){
        end();
    };
    self.changePageBlock = ^(){
        changPage();
    };
    [self addSubview:self.loopProgressView];
    UITapGestureRecognizer *hopTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endCurrentPage)];
    [self.loopProgressView addGestureRecognizer:hopTap];
}
- (void) endCurrentPage{
    [_timer invalidate];
    _timer = nil;
    if (_endBlock) {
        _endBlock();
    }
    [self removeFromSuperview];
}

- (void) createTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(downloadCurrent) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void) downloadCurrent {
    pathValue += .1/5.;
    [self.loopProgressView drawProgress:pathValue];
    if (pathValue >= 1.) {
        [_timer invalidate];
        _timer = nil;
        if (_endBlock) {
            _endBlock();
        }
        [self removeFromSuperview];
    }
}

- (void) changePage {
    [_timer invalidate];
    _timer = nil;
    if (_changePageBlock) {
        _changePageBlock();
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary * currentDic = [userDefaults valueForKey:@"tableScreenData"];
    [_model createOtherAdvertOclick:currentDic];
    JSTAdWebViewController *webView = [[JSTAdWebViewController alloc] init];
    webView.urlStr = currentDic[@"url"];
    webView.pushData = currentDic;
    [[self getViewCtl].navigationController pushViewController:webView animated:YES];
    [self removeFromSuperview];
}

- (UIViewController *) getViewCtl{
    for (UIView *next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

- (JSTLoopProgressView *)loopProgressView
{
    if (!_loopProgressView) {
        _loopProgressView = [[JSTLoopProgressView alloc] init];
        _loopProgressView.frame = CGRectMake(kDeviceWidth - kCurrentScreenWidth(10) - kCurrentScreenWidth(50), kCurrentScreenWidth(20), kCurrentScreenWidth(50), kCurrentScreenWidth(50));
        _loopProgressView.layer.masksToBounds = YES;
        _loopProgressView.layer.cornerRadius = kCurrentScreenWidth(50)/2.;
    }
    return _loopProgressView;
}

- (UIImageView *)adImgView
{
    if (!_adImgView) {
        _adImgView = [[UIImageView alloc] init];
        _adImgView.userInteractionEnabled = YES;
        _adImgView.frame = CGRectMake(0, 0, kDeviceWidth, kDeviceHeight - kDeviceWidth*200/750.);
        _adImgView.myLeftMargin = _adImgView.myRightMargin = 0;
    }
    return _adImgView;
}

- (UIImageView *)otherImgView{
    if (!_otherImgView) {
        _otherImgView = [[UIImageView alloc] init];
        _otherImgView.frame = CGRectMake(0, CGRectGetMaxY(self.adImgView.frame), kDeviceWidth, kDeviceWidth*200/750.);
        _otherImgView.myLeftMargin = _otherImgView.myRightMargin = 0;
    }
    return _otherImgView;
}
@end

@interface JSTLoopProgressView()
@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, strong) CAShapeLayer *progressLayer;
@end
@implementation JSTLoopProgressView

- (UILabel *)label
{
    if (_label == nil) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(2.5, 2.5, self.width - 2.5*2, self.height - 2.5*2)];
        label.textAlignment = NSTextAlignmentCenter;
        label.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
        label.text = @"跳过";
        label.font = kSystemFont(self.width/4.);
        label.textColor = [UIColor whiteColor];
        [self addSubview:label];
        _label = label;
    }
    return _label;
}

- (void)drawProgress:(CGFloat )progress
{
    _progress = progress;
    _progressLayer.opacity = 0;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    
    [self drawCycleProgress];
    [self label];
}

- (void)drawCycleProgress
{
    CGPoint center = CGPointMake(kCurrentScreenWidth(50)/2., kCurrentScreenWidth(50)/2.);
    CGFloat radius = kCurrentScreenWidth(48)/2.;
    CGFloat startA = - M_PI_2;
    CGFloat endA = -M_PI_2 + M_PI * 2 * _progress;
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.frame = self.bounds;
    _progressLayer.fillColor = [[UIColor clearColor] CGColor];
    _progressLayer.strokeColor = [[UIColor redColor] CGColor];
    _progressLayer.opacity = 1;
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.lineWidth = 2.5;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    _progressLayer.path =[path CGPath];
    [self.layer addSublayer:_progressLayer];
}

@end
